package com.cloudcross.ssp.web.advertiser.main.finance;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.AdvBalance;
import com.cloudcross.ssp.service.IAdvAgentService;
import com.cloudcross.ssp.service.IAdvBalanceService;
import com.cloudcross.ssp.service.IAdvertiserService;

@Controller
@RequestMapping("/advertiser/main/finance/adv-balance")
public class AdvBalanceController extends SimpleController {
    @Autowired
    protected IAdvBalanceService advBalanceService;
    @Autowired
    private FreemarkerTemplateProcessor templateProcessor;
    @Autowired
    private IAdvAgentService advAgentService;
    @Autowired
    private IAdvertiserService advertiserService;

    @RequestMapping
    public String index() {
        return redirect(page("list"));
    }

    /**
     * 财务管理列表页
     * 前端需要传递三个参数，一个为广告主id(变量名为selectedAdvertiserId)如果传的是空值或者是-1或者空字符串则为全部
     * 一个为类型，变量名为type，最后一个为周期，变量名为dateRangePicker
     * 注：当如果是代理商账号登录的时候只能查询到分配记录和充值记录不能查询到消费记录 如果是广告主账号登录只能看到分配记录和消费记录没有充值记录
     * 
     * @param model
     * @param paramMap
     * @param page
     * @return
     * @throws ParseException
     */
    @RequestMapping("/list")
    public String list(Model model, @RequestParam HashMap<String, Object> paramMap, @RequestParam(defaultValue = "1") int page)
            throws ParseException {
        Long advertiserId = null;
        Long agentId = null;
        String advertiserName = "全部广告主";

        // 获取当前登录的帐号
        Account account = getLoginUser();
        model.addAttribute("loginAccountName", account.getAccountName());
        model.addAttribute("advertiserIdFinance", account.getAdvertiserId());
        /**
         * 对登录的账号进行判断，如果代理商id和广告主id都不为0的话表示的是广告主账号 如果代理商账号不为0，广告主账号为0的话表示的是代理商账号
         */
        // 下面判断是广告主
        if (0 != account.getAdvertiserId() && 0 != account.getAgentId()) {
            paramMap.put("accountId", account.getId());
            advertiserId = account.getAdvertiserId();
        }

        // 下面判断是代理商
        if (0 != account.getAgentId() && 0 == account.getAdvertiserId()) {
            paramMap.put("accountId", account.getId());
        }

        agentId = account.getAgentId();
        
        /**
         * 下面对传递进来的参数进行处理
         */
        if (null == paramMap.get("selectedAdvertiserId") || "".equals(paramMap.get("selectedAdvertiserId"))) {
            advertiserName = "全部广告主";
        } else {
            // 如果要查询的是所有广告主则让广告主id为空
            if (-1 == Long.parseLong((String) paramMap.get("selectedAdvertiserId"))) {
                advertiserName = "全部广告主";
            } else {
                advertiserId = Long.parseLong((String) paramMap.get("selectedAdvertiserId"));
                advertiserName = (String) paramMap.get("selectedAdvertiserName");
            }
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String startDate = null;
        String endDate = null;
        // 判断日期是否为默认值昨天，日期格式为2015-09-09 to 2015-10-10，用 to 分割
        if (null == paramMap.get("dateRangePicker") || "".equals(paramMap.get("dateRangePicker"))) {
            startDate = endDate = sdf.format(new Date((new Date()).getTime() - 24 * 60 * 60 * 1000));
        } else {
            String[] choosedDate = ((String) paramMap.get("dateRangePicker")).split("to");
            startDate = choosedDate[0].trim();
            endDate = choosedDate[1].trim();
        }

        /**
         * @author Hao 选择操作类型，需要从前端传过来一个键值对“type”,默认为null
         *         其值与allocate，consume，chage比较确定是选择了哪一类
         */
        String type = null;
        String typeName = "请选择操作类型";
        if (null == paramMap.get("type") || "".equals(paramMap.get("type")) || "0".equals(paramMap.get("type"))) {
            type = "0";
            typeName = "请选择操作类型";
        } else if ("allocate".equals(paramMap.get("type"))) {
            type = "allocate";
            typeName = "分配";
        } else if ("consume".equals(paramMap.get("type"))) {
            type = "consume";
            typeName = "消费";
        } else {
            type = "charge";
            typeName = "充值";
        }

        paramMap.put("startDate", startDate);
        paramMap.put("endDate", endDate);
        paramMap.put("agentId", agentId);
        paramMap.put("advertiserId", advertiserId);
        paramMap.put("selectedAdvertiserName", advertiserName);
        paramMap.put("type", type);
        paramMap.put("typeName", typeName);

        int totalRow = advBalanceService.countByParams(paramMap);
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<AdvBalance> advBalanceList = advBalanceService.findByParams(paramMap, pager);

        if (null != agentId) {
            model.addAttribute("agentName", advAgentService.findById(agentId).getName());
        }
        model.addAllAttributes(paramMap);
        model.addAttribute("pager", pager);
        model.addAttribute("advBalanceList", advBalanceList);
        return page("list");
    }

    /**
     * 广告主分配记录页面
     * 前端需要传递两个参数，一个为广告主id(变量名为selectedAdvertiserId)如果传的是空值或者是-1或者空字符串则为全部
     * 另一个为周期，变量名为dateRangePicker 注：如果选择的广告主表示全部广告主的话，则显示的是代理商的分配记录，否则是广告主的分配记录
     * 
     * @param model
     * @param paramMap
     * @param page
     * @return
     * @throws ParseException
     */
    @RequestMapping("/distribution")
    public String distribution(Model model, @RequestParam HashMap<String, Object> paramMap, @RequestParam(defaultValue = "1") int page)
            throws ParseException {

        Long agentId = null;
        Long advertiserId = null;

        // 获取当前登录的帐号
        Account account = getLoginUser();
        model.addAttribute("loginAccountName", account.getAccountName());
        model.addAttribute("advertiserIdFinance", account.getAdvertiserId());

        /*
         * 判断登录用户是广告主还是广告主代理商，广告主则advertiserId和agentId都不为0
         * 广告主代理商则是agentId不为0，advertiserId等于0
         */
        // 下面判断是广告主
        if (0 != account.getAdvertiserId() && 0 != account.getAgentId()) {
            paramMap.put("accountId", account.getId());
            advertiserId = account.getAdvertiserId();
        }

        // 下面判断是代理商
        if (0 != account.getAgentId() && 0 == account.getAdvertiserId()) {
            paramMap.put("accountId", account.getId());
            agentId = account.getAgentId();
        }

        /**
         * 下面对传进来的值进行处理
         */
        String advertiserName = "全部广告主";
        if (null == paramMap.get("selectedAdvertiserId") || "".equals(paramMap.get("selectedAdvertiserId"))) {
            advertiserName = "全部广告主";
        } else {
            // 如果要查询的是所有广告主则让广告主id为空
            if (-1 == Long.parseLong((String) paramMap.get("selectedAdvertiserId"))) {
                advertiserName = "全部广告主";
            } else {
                advertiserId = Long.parseLong((String) paramMap.get("selectedAdvertiserId"));
                advertiserName = (String) paramMap.get("selectedAdvertiserName");
            }
        }

        // 日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String startDate = null;
        String endDate = null;
        // 判断日期是否为默认值昨天，日期格式为2015-09-09 to 2015-10-10，用 to 分割
        if (null == paramMap.get("dateRangePicker") || "".equals(paramMap.get("dateRangePicker"))) {
            startDate = endDate = sdf.format(new Date((new Date()).getTime() - 24 * 60 * 60 * 1000));
        } else {
            String[] choosedDate = ((String) paramMap.get("dateRangePicker")).split("to");
            startDate = choosedDate[0].trim();
            endDate = choosedDate[1].trim();
        }

        paramMap.put("agentId", agentId);
        paramMap.put("advertiserId", advertiserId);
        paramMap.put("selectedAdvertiserName", advertiserName);
        paramMap.put("startDate", startDate);
        paramMap.put("endDate", endDate);

        int totalRow = advBalanceService.countByParams2(paramMap);
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<AdvBalance> advBalanceList = advBalanceService.findByParams2(paramMap, pager);

        if (null != agentId) {
            model.addAttribute("agentName", advAgentService.findById(agentId).getName());
        }
        model.addAllAttributes(paramMap);
        model.addAttribute("pager", pager);
        model.addAttribute("advBalanceList", advBalanceList);
        return page("distribution");
    }

    /**
     * 财务管理列表页导出excel
     * 前端需要传递三个参数，一个为广告主id(变量名为selectedAdvertiserId)如果传的是空值或者是-1或者空字符串则为全部
     * 一个为类型，变量名为type，最后一个为周期，变量名为dateRangePicker
     * 注：当如果是代理商账号登录的时候只能查询到分配记录和充值记录不能查询到消费记录 如果是广告主账号登录只能看到分配记录和消费记录没有充值记录
     * 
     * @param model
     * @param request
     * @param response
     * @param paramMap
     */
    @RequestMapping("/exportDataReportExcel")
    public void exportDataReportExcel(Model model, HttpServletRequest request, HttpServletResponse response,
            @RequestParam Map<String, Object> paramMap) {

        Long advertiserId = null;
        Long agentId = null;
        String advertiserName = "全部广告主";

        // 获取当前登录的帐号
        Account account = getLoginUser();
        model.addAttribute("loginAccountName", account.getAccountName());

        /**
         * 对登录的账号进行判断，如果代理商id和广告主id都不为0的话表示的是广告主账号 如果代理商账号不为0，广告主账号为0的话表示的是代理商账号
         */
        // 下面判断是广告主
        if (0 != account.getAdvertiserId() && 0 != account.getAgentId()) {
            paramMap.put("accountId", account.getId());
            advertiserId = account.getAdvertiserId();
        }

        // 下面判断是代理商
        if (0 != account.getAgentId() && 0 == account.getAdvertiserId()) {
            paramMap.put("accountId", account.getId());
            agentId = account.getAgentId();
        }

        /**
         * 下面对传递进来的参数进行处理
         */
        if (null == paramMap.get("selectedAdvertiserId") || "".equals(paramMap.get("selectedAdvertiserId"))) {
            advertiserName = "全部广告主";
        } else {
            // 如果要查询的是所有广告主则让广告主id为空
            if (-1 == Long.parseLong((String) paramMap.get("selectedAdvertiserId"))) {
                advertiserName = "全部广告主";
            } else {
                advertiserId = Long.parseLong((String) paramMap.get("selectedAdvertiserId"));
                advertiserName = advertiserService.findById(advertiserId).getName();
            }
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String startDate = null;
        String endDate = null;
        // 判断日期是否为默认值昨天，日期格式为2015-09-09 to 2015-10-10，用 to 分割
        if (null == paramMap.get("dateRangePicker") || "".equals(paramMap.get("dateRangePicker"))) {
            startDate = endDate = sdf.format(new Date((new Date()).getTime() - 24 * 60 * 60 * 1000));
        } else {
            String[] choosedDate = ((String) paramMap.get("dateRangePicker")).split("to");
            startDate = choosedDate[0].trim();
            endDate = choosedDate[1].trim();
        }

        /**
         * @author Hao 选择操作类型，需要从前端传过来一个键值对“type”,默认为null
         *         其值与allocate，consume，chage比较确定是选择了哪一类
         */
        String type = null;
        String typeName = "请选择操作类型";
        if (null == paramMap.get("type") || "".equals(paramMap.get("type")) || "0".equals(paramMap.get("type"))) {
            type = "0";
            typeName = "请选择操作类型";
        } else if ("allocate".equals(paramMap.get("type"))) {
            type = "allocate";
            typeName = "分配";
        } else if ("consume".equals(paramMap.get("type"))) {
            type = "consume";
            typeName = "消费";
        } else {
            type = "charge";
            typeName = "充值";
        }

        paramMap.put("startDate", startDate);
        paramMap.put("endDate", endDate);
        paramMap.put("agentId", agentId);
        paramMap.put("advertiserId", advertiserId);
        paramMap.put("selectedAdvertiserName", advertiserName);
        paramMap.put("type", type);
        paramMap.put("typeName", typeName);
        if (null != agentId) {
            paramMap.put("agentName", advAgentService.findById(agentId).getName());
        }
        List<AdvBalance> advBalanceList = advBalanceService.findByParamsAdvertiser(paramMap);

        paramMap.put("dataList", advBalanceList);
        response.reset();
        // Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
        response.setContentType("application/vnd.ms-excel;charset=utf8");
        // 设置excel文件名称
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "consumeReport" + df2.format(new Date());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        // 需要对excel的列的总数进行指定
        int column = 10;
        paramMap.put("dataSize", (advBalanceList.size() + 100));
        paramMap.put("column", column);
        String excelOrder = templateProcessor.processTemplate("excel/consumeReport.ftl", paramMap);
        try {
            PrintWriter out = response.getWriter();
            out.write(excelOrder);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 广告主分配记录导出excel
     * 
     * @param model
     * @param request
     * @param response
     * @param paramMap
     */
    @RequestMapping("/exportAllocateReportExcel")
    public void exportAllocateReportExcel(Model model, HttpServletRequest request, HttpServletResponse response,
            @RequestParam Map<String, Object> paramMap) {
        Long agentId = null;
        Long advertiserId = null;
        // 获取当前登录的帐号
        Account account = getLoginUser();
        model.addAttribute("loginAccountName", account.getAccountName());
        /**
         * 判断登录用户是广告主还是广告主代理商，广告主则advertiserId和agentId都不为0
         * 广告主代理商则是agentId不为0，advertiserId等于0
         */
        // 下面判断是广告主
        if (0 != account.getAdvertiserId() && 0 != account.getAgentId()) {
            paramMap.put("accountId", account.getId());
            advertiserId = account.getAdvertiserId();
        }

        // 下面判断是代理商
        if (0 != account.getAgentId() && 0 == account.getAdvertiserId()) {
            paramMap.put("accountId", account.getId());
            agentId = account.getAgentId();
        }

        /**
         * 下面对传进来的值进行处理
         */
        String advertiserName = "全部广告主";
        if (null == paramMap.get("selectedAdvertiserId") || "".equals(paramMap.get("selectedAdvertiserId"))) {
            advertiserName = "全部广告主";
        } else {
            // 如果要查询的是所有广告主则让广告主id为空
            if (-1 == Long.parseLong((String) paramMap.get("selectedAdvertiserId"))) {
                advertiserName = "全部广告主";
            } else {
                advertiserId = Long.parseLong((String) paramMap.get("selectedAdvertiserId"));
                advertiserName = advertiserService.findById(advertiserId).getName();
            }
        }

        // 日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String startDate = null;
        String endDate = null;
        // 判断日期是否为默认值昨天，日期格式为2015-09-09 to 2015-10-10，用 to 分割
        if (null == paramMap.get("dateRangePicker") || "".equals(paramMap.get("dateRangePicker"))) {
            startDate = endDate = sdf.format(new Date((new Date()).getTime() - 24 * 60 * 60 * 1000));
        } else {
            String[] choosedDate = ((String) paramMap.get("dateRangePicker")).split("to");
            startDate = choosedDate[0].trim();
            endDate = choosedDate[1].trim();
        }

        paramMap.put("agentId", agentId);
        paramMap.put("advertiserId", advertiserId);
        paramMap.put("selectedAdvertiserName", advertiserName);
        paramMap.put("startDate", startDate);
        paramMap.put("endDate", endDate);

        List<AdvBalance> advBalanceList2 = advBalanceService.findByParams2(paramMap);
        paramMap.put("dataList", advBalanceList2);
        response.reset();
        // Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
        response.setContentType("application/vnd.ms-excel;charset=utf8");
        // 设置excel文件名称
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "allocateReport" + df2.format(new Date());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        // 需要对excel的列和行的总数进行指定
        int column = 10;
        paramMap.put("dataSize", (advBalanceList2.size() + 100));
        paramMap.put("column", column);
        String excelOrder = templateProcessor.processTemplate("excel/allocateReport.ftl", paramMap);
        try {
            PrintWriter out = response.getWriter();
            out.write(excelOrder);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
